package cn.colins.raft;

import cn.colins.raft.config.ServerConfig;
import cn.colins.raft.enity.RaftNodeInfo;
import cn.colins.raft.log.SimpleLogManage;
import cn.colins.raft.node.RaftNodeService;
import cn.colins.raft.rpc.RpcClient;
import cn.colins.raft.rpc.RpcServer;
import cn.colins.raft.rpc.session.RpcSessionFactory;
import cn.colins.raft.task.ElectionTask;
import cn.colins.raft.task.LogIndexCheckTask;
import cn.colins.raft.utils.ThreadPoolUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description raft 服务类
 * @Author czl
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2023/7/18
 */
public class RaftService implements ResourceLifeCycle {

    private ServerConfig selfConfig;

    private List<ServerConfig> clusterList;

    private RpcServer rpcServer;

    private String logPath;

    public RaftService(ServerConfig selfConfig, List<ServerConfig> clusterList, String logPath) {
        this.clusterList = clusterList;
        this.selfConfig = selfConfig;
        this.logPath = logPath;
    }


    @Override
    public void init() {
        // 节点初始化
        RaftNodeService.raftNodeInit(selfConfig, clusterList);
        RaftNodeInfo.getInstance().setLogPath(logPath);
        // 日志模块初始化
        SimpleLogManage simpleLogManage = new SimpleLogManage(logPath);
        simpleLogManage.init();
        // 开启logCheck任务 30s检测一次
        ThreadPoolUtils.logPullAsyncPool.scheduleWithFixedDelay(new LogIndexCheckTask(), 15L, 30L, TimeUnit.SECONDS);
        // 服务端初始化
        rpcServer = new RpcServer(selfConfig.getPort());
        rpcServer.init();
    }

    @Override
    public void destroy() {
        RaftNodeService.electionTaskDestroy();
        RaftNodeService.heartBeatTestDestroy();
        if (rpcServer != null) {
            rpcServer.destroy();
        }
        LogManage logManage = RaftNodeInfo.getInstance().getLogManage();
        if (logManage != null) {
            logManage.destroy();
        }
        // 释放所有和其他节点的连接
        RpcSessionFactory.channelClear();
    }
}
